/**
 * echart同步操作，如缩放，点击图例
 */

import { isNum, visualAction } from '@/utils/util';
import { mapMutations } from 'vuex';
import { isEqual } from 'lodash';

export default {
  data() {
    return {
      actionUnwatchs: {},
    };
  },

  computed: {
    echartActions: state => state.VisualComponentsModule.echartActions,
    sharedActions() {
      if (!this.config) {
        return [];
      }
      const { echart } = this.config.config.property;
      const _sharedActions = (echart && echart._sharedActions) || [];
      return _sharedActions;
    },
  },

  watch: {
    sharedActions() {
      this.watchEchartActions();
    },
  },
  methods: {
    ...mapMutations(['setState']),

    // echart同步操作 - vuex初始化
    initEchartActions() {
      if (this.sharedActions.length) {
        const EA = JSON.parse(JSON.stringify(this.echartActions));
        const wid = this.widgetInstanceId;
        this.sharedActions.forEach(n => {
          if (!n.type || !n.key) {
            return true;
          }
          const { type } = n;
          if (!EA[type]) {
            EA[type] = {};
          }
          if (!EA[type][wid]) {
            EA[type][wid] = {};
          }
          EA[type][wid] = { key: n.key, val: null };
          return true;
        });
        this.setState({ echartActions: EA });
      }
    },

    // echart同步操作 - vuex => 图
    watchEchartActions() {
      if (this.sharedActions.length) {
        const wid = this.widgetInstanceId;

        // 注销watch
        Object.entries(this.actionUnwatchs).map(([i]) => {
          this.actionUnwatchs[i]();
        });

        this.sharedActions.forEach(n => {
          this.actionUnwatchs[n.type] = this.$watch(`echartActions.${n.type}`, (newVal, oldVal) => {
            if (isEqual(newVal, oldVal)) {
              return;
            }
            const chart = this.$refs.dataChart && this.$refs.dataChart.chart;
            const { outWid } = this.echartActions;

            if (chart && outWid !== wid) {
              const { key, val } = newVal[wid];
              if (n.type === 'dataZoomX') {
                isNum(val.start) &&
                  isNum(val.end) &&
                  chart.dispatchAction({
                    type: 'dataZoom',
                    start: val.start,
                    end: val.end,
                  });
              }
              if (n.type === 'legend') {
                const _type = val.isSelected ? 'legendSelect' : 'legendUnSelect';
                chart.dispatchAction({
                  type: _type,
                  name: val.name,
                });
              }
            }
          });
        });
      }
    },

    // echart同步操作 - 图 => vuex
    onEchartActions() {
      this.onDataZoomX();
      this.onLegendClick();
    },

    // x轴缩放
    onDataZoomX() {
      const ev = this.sharedActions.find(n => n.type === 'dataZoomX');
      if (ev) {
        const chart = this.$refs.dataChart && this.$refs.dataChart.chart;
        if (!chart) {
          return;
        }

        const { slider } = this.config.config.property.echart.dataZoom;
        const { show, start } = slider;
        let { end } = slider;
        if (!show) {
          // 不显示滚动条，取所有滚动条最小值
          end = 100;
          const EA = this.echartActions;
          Object.entries(EA.dataZoomX).map(([i]) => {
            const n = EA.dataZoomX[i];
            if (n.val) {
              end = n.val.end < end ? n.val.end : end;
            }
          });
        }

        chart.on('dataZoom', params => {
          const { batch } = params;
          const _start = params.start || (batch && batch[0] && batch[0].start) || 0;
          const _end = params.end || (batch && batch[0] && batch[0].end) || 100;
          clearTimeout(this.timers.dataZoomX);
          this.timers.dataZoomX = setTimeout(() => {
            this.syncActState('dataZoomX', ev.key, {
              start: _start,
              end: _end,
            });
          }, 50);
        });

        if (show) {
          chart.dispatchAction({
            type: 'dataZoom',
            start: 0,
            end: end,
          });
        }
      }
    },

    // 图例点击
    onLegendClick() {
      const shareEv = this.sharedActions.find(n => n.type === 'legend');
      const chart = this.$refs.dataChart && this.$refs.dataChart.chart;
      chart &&
        chart.on('legendselectchanged', params => {
          if (shareEv) {
            const { name, selected } = params;
            const isSelected = selected[name];
            this.syncActState('legend', shareEv.key, { name, isSelected });
          }
          visualAction('clickLegend', 100);
        });
    },

    syncActState(type, key, val) {
      const EA = JSON.parse(JSON.stringify(this.echartActions));
      const wid = this.widgetInstanceId;
      EA.outWid = wid;

      Object.entries(EA[type]).map(([i]) => {
        const n = EA[type][i];
        if (n.key === key) {
          n.val = val;
        }
      });
      this.setState({ echartActions: EA });
    },
  },
};
